package logic

import (
	"context"
	"fmt"
	"vip-shop/cache"
	"vip-shop/model"

	"vip-shop/shoprpc/internal/svc"
	"vip-shop/shoprpc/shoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpDataLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpDataLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpDataLogic {
	return &UpDataLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpDataLogic) UpData(in *shoprpc.UpDataRequest) (*shoprpc.UpDataResponse, error) {
	// todo: add your logic here and delete this line
	var user model.User
	model.DB.Where("mobile=?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("用户未注册")
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("原密码错误")
	}
	if user.Password == in.NewPassword {
		return nil, fmt.Errorf("原密码与新密码一致")
	}
	s, _ := cache.Rdb.Get(cache.Ctx, "sms"+in.Account).Result()
	if in.SenSmsCode != s {
		return nil, fmt.Errorf("短信验证码错误")
	}
	user = model.User{
		Mobile:   in.Account,
		Password: in.NewPassword,
	}
	model.DB.Updates(user)
	return &shoprpc.UpDataResponse{
		UserId: int64(user.ID),
	}, nil
}
